package com.xianban.filter;

import com.alibaba.fastjson.JSON;
import com.xianban.common.BaseContext;
import com.xianban.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author banxian
 * @data 2023/1/17 21:17
 */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilters implements Filter {
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    /**
     * 获取本次请求URI
     * 定义不需要拦截的
     * PATH_MATCHER:路径匹配器支持通配符
     * 路径匹配
     * 判断登录状态是否需要放行
     * 通过输出流方式向客户端响应数据
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        String requestURI = request.getRequestURI();
        log.info("11111: {}",requestURI);
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        boolean check = check(urls, requestURI);
        if (check){
            filterChain.doFilter(request,response);
            return;
        }

        /**
         * services is login?
         */
        if (request.getSession().getAttribute("employee")!=null){
            Long employeeId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(employeeId);
            filterChain.doFilter(request,response);
            return;
        }

        /**
         * user is login?
         */
        if (request.getSession().getAttribute("user")!=null){
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
    public boolean check(String [] urls,String requestUri){
        for (String url : urls) {
           boolean mach= PATH_MATCHER.match(url,requestUri);
           if (mach){
               return true;
           }
        }
        return false;
    }
}
